package build_dao

import (
	"go_server/game_server/database/mysql"
	"go_server/zinx/zlog"
	"go_server/zinx/zutils"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type BuildUpgrade struct {
	Id          string `gorm:"column:Id;primary"`
	UpgradeTime int64  `gorm:"column:upgrade_time"`
	CreateTime int64 `gorm:"column:create_time"`
	RoleId int64 `gorm:"column:role_id"`
}

func (BuildUpgrade) TableName() string {
	return "build_upgrade"
}

var (
	all_build_upgrade_field = zutils.GetGormFields(BuildUpgrade{})
)

func NewBuildUpgrade(createMap map[string][]int64, roleId int64) {
	if len(createMap) <= 0 {
		return
	}
	buildArr := make([]*BuildUpgrade, 0, len(createMap))
	for key, createTime := range createMap {
		buildObj := &BuildUpgrade{
			Id:          key,
			UpgradeTime: createTime[1],
			CreateTime: createTime[0],
			RoleId: roleId,
		}
		buildArr = append(buildArr, buildObj)
	}

	db := mysql.GetServerDBConnection()
	if err := db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "id"}},
		DoUpdates: clause.AssignmentColumns([]string{"upgrade_time", "create_time"}),
	}).Create(buildArr).Error; err != nil {
		zlog.Errorf("create BuildUpgrade %v data failed: %v", buildArr, err)
	}
}

func GetBuildUpgradeByRoleId(roleId int64) []*BuildUpgrade {
	db := mysql.GetServerDBConnection()
	var buildCreates []*BuildUpgrade
	if err := db.Select(all_build_upgrade_field).Where("role_id=?", roleId).Find(&buildCreates).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetBuildUpgradeByRoleId ERR!!! role_id: %d, err: %v", roleId, err)
		}
		return nil
	}
	return buildCreates
}
